import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:interview/servers/opt_list.dart';
import 'package:interview/servers/question_list.dart';
import 'package:interview/utils/logger.dart';

class OptState {
  final RxList<Question> optList = <Question>[].obs;
  final RxBool isFinished = false.obs; // 是否加载完成
  final RxBool isLoading = false.obs; // 是否正在加载中
  int currentPage = 1; // 当前页码
  int pageTotal = 1; // 总页数

  void reset() {
    optList.clear();
    isFinished.value = false;
    currentPage = 1;
  }
}

class OptlistController {
  final RxMap<int , OptState> optState = <int , OptState>{}.obs;


  OptState getPageState(int optType) {
    optState.putIfAbsent(optType, () => OptState());
    return optState[optType]!;
  }
  

  Future<void> _fetchOptLists({
    required BuildContext context,
    required int optType,
    required int questionBankType,
    required OptState state
  }) async {
    try {
      final params = OptListParams(
        optType: optType, 
        pageSize: 10, 
        page: state.currentPage, 
        questionBankType: questionBankType
      );

      final result = await fetchOptList(params, context);

       // 处理结果
      if (result.questions.isNotEmpty) {
        state.optList.addAll(result.questions);
        state.pageTotal = result.pageTotal;
        state.currentPage++;
        state.isFinished.value = state.currentPage > state.pageTotal;
      } else {
        state.isFinished.value = true;
      }
    } catch (e) {
      Logger.error("加载optlist失败: $e", tag: "fetchQuestions");
    }
  }


  // 加载更多数据
  Future <void> loadOptList({
    required BuildContext context,
    required int optType,
    required int questionBankType,
  })async {
    final state = getPageState(optType);
    if(state.isLoading.value || state.isFinished.value) return ;
    state.isLoading.value = true;
    await _fetchOptLists(
      context: context, 
      optType: optType, 
      questionBankType: questionBankType, 
      state: state
    );
    state.isLoading.value = false;
  }


  // 刷新数据
  Future<void> refreshOptList({
    required BuildContext context,
    required int optType,
    required int questionBankType,
  }) async {
    final state = getPageState(optType);
    if (state.isLoading.value) return;
    state.isLoading.value = true;
    state.reset();
    await _fetchOptLists(
      context: context, 
      optType: optType, 
      questionBankType: 
      questionBankType, 
      state: state
    );
    state.isLoading.value = false;
  }


}